
/*
 *
 * Copyright (C) 2008 Mattias Blomqvist, patr-blo at dsv dot su dot se
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using ClientExample.Controls;
using ClientExample.Containers;
using FlowLib.Events;

namespace ClientExample.Client.Interface
{
    public partial class MessageWindow : System.Windows.Forms.Form
    {
        protected Queue<Message> messages = new Queue<Message>();
        protected System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        protected bool isUpdating = false;
        protected SortedList<string, HubControl> hubs = new SortedList<string, HubControl>();
        protected FlowLib.Containers.PropertyContainer<string, object> settingChange = new FlowLib.Containers.PropertyContainer<string, object>();
        protected System.Windows.Forms.TabPage tabNoMessage = new System.Windows.Forms.TabPage();

        public new bool Close
        {
            get;
            set;
        }

        public MessageWindow()
        {
            Close = false;
			IntPtr h = Handle;  // This is for stupid mono stuff. Some how handle isnt created correctly if we dont do this :(
            InitializeComponent();

            // Add no message tab
            OneMessageControl noMsg = new OneMessageControl();
            noMsg.Text = "No new messages";
            noMsg.Dock = System.Windows.Forms.DockStyle.Fill;
            tabNoMessage.Controls.Add(noMsg);
            AddNoMessage();

            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = 100;
            timer.Start();

            this.KeyUp += new System.Windows.Forms.KeyEventHandler(MessageWindow_KeyUp);

            tabControl1.MouseClick += new System.Windows.Forms.MouseEventHandler(tabControl1_MouseClick);
        }


        private void AddNoMessage()
        {
            tabControl1.TabPages.Add(tabNoMessage);
        }

        private void RemoveNoMessage()
        {
            tabControl1.TabPages.Remove(tabNoMessage);
        }

        public void AddHub(HubControl hub)
        {
            try
            {
                hub.HubUpdate += new FlowLib.Events.FmdcEventHandler(hub_HubUpdate);
                hubs.Add(hub.Id, hub);
            }
            catch (ArgumentException)
            {
                hub.HubUpdate -= hub_HubUpdate;
                hub.Dispose();
                // TODO : Make a better information box
                System.Windows.Forms.MessageBox.Show(string.Format("You have duplicate connections to:{0} - {1}.\r\n One of the connections will be disconnected.", hub.Id, hub.TopLabel.Text));
            }
        }

        public MessageTab AddMessage(Message msg)
        {
            MessageTab tab = null;
            lock (tabControl1)
            {
                if (tabControl1.TabPages.ContainsKey(msg.GroupId))
                {
                    tab = (MessageTab)tabControl1.TabPages[msg.GroupId];
                }
                else
                {
                    tab = new MessageTab();
                    tab.Name = msg.GroupId;
                    tab.Text = msg.GroupName;
                    tab.MessagePanel.ActionUpdate += new FmdcEventHandler(MessagePanel_ActionUpdate);
                    tabControl1.TabPages.Add(tab);
                    if (tabNoMessage.Parent != null)
                    {
                        RemoveNoMessage();
                    }
                }
            }

            tab.Info = msg.Status;
            tab.MessagePanel.AddMessage(msg);
            return tab;
        }

        void MessageWindow_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            //if (e.Alt)
            toolStrip1.Visible = !toolStrip1.Visible;
        }

        void tabControl1_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                lock (tabControl1.TabPages)
                {
                    for (int i = 0; i < tabControl1.TabCount; i++)
                    {
                        Rectangle rec = tabControl1.GetTabRect(i);
                        if (rec.Contains(e.Location))
                        {
                            tabControl1.TabPages.RemoveAt(i);
                            if (tabControl1.TabCount == 0)
                            {
                                AddNoMessage();
                            }
							tabControl1.Invalidate(true);
                            break;
                        }
                    }
                }
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (isUpdating)
                return;
            isUpdating = true;

            if (messages.Count > 0)
            {
                Message msg = messages.Dequeue();
                AddMessage(msg);
            }

            isUpdating = false;
        }

        void MessagePanel_ActionUpdate(object sender, FmdcEventArgs e)
        {
            OnlineStatus status = sender as OnlineStatus;
            Message msg = e.Data as Message;
            if (status == null || msg == null)
                return;
            if (hubs.ContainsKey(status.HubId))
            {
                lock (hubs)
                {
                    HubControl hub = hubs[status.HubId];
                    hub.SendMessage(msg);
                }
            }
        }

        void hub_HubUpdate(object sender, FlowLib.Events.FmdcEventArgs e)
        {
            Message msg = null;
            MessageTab tab = null;
            switch (e.Action)
            {
                case Actions.MainMessage:
                case Actions.PrivateMessage:
                    msg = e.Data as Message;
                    if (msg == null)
                        return;
                    messages.Enqueue(msg);
                    break;
                case EventActions.ForceOpenMessage:
                    msg = e.Data as Message;
                    if (msg == null)
                        return;
                    tab = AddMessage(msg);
                    tabControl1.SelectedTab = tab;
                    //tab.Select();
                    break;
                case EventActions.SettingsChange:
                    settingChange.Set(e.Data.ToString(), "1");
                    break;
                case EventActions.OnlineStatusChange:      // Update Status
                    OnlineStatus onlineStatus = e.Data as OnlineStatus;
                    if (onlineStatus == null)
                        return;
                    // Do message tab exist?
                    if (tabControl1.TabPages.ContainsKey(onlineStatus.HubId + onlineStatus.UserId))
                    {
                        // Change Online status for User and for hubs not set to offline
                        if (onlineStatus.UserId != null || onlineStatus.Status != FlowLib.Connections.TcpConnection.Disconnected)
                        {
                            lock (tabControl1.TabPages)
                            {
                                tab = (MessageTab)tabControl1.TabPages[onlineStatus.HubId + onlineStatus.UserId];
                                if (tab != null)
                                {
                                    tab.Info = onlineStatus;
                                }
                            }
                        }
                        else if (onlineStatus.Status == FlowLib.Connections.TcpConnection.Disconnected)
                        {
                            // Hub that we want to set as offline
                            lock (tabControl1.TabPages)
                            {
                                // Loop through all messagetabs and set offline mode for messages from this hub.
                                foreach (MessageTab msgTab in tabControl1.TabPages)
                                {
                                    if (onlineStatus.HubId.Equals(msgTab.Info.HubId))
                                    {
                                        OnlineStatus tmpStatus = onlineStatus;
                                        tmpStatus.HubId = msgTab.Info.HubId;
                                        tmpStatus.UserId = msgTab.Info.UserId;
                                        msgTab.Info = tmpStatus;
                                        // Save hub Message tab for later use
                                        if (msgTab.Info.UserId == null)
                                            tab = msgTab;
                                    }
                                }
                            }

                            // Is hub object trying to dispose it self?
                            HubControl hub = null;
                            lock (hubs)
                            {
                                hub = hubs[onlineStatus.HubId];
                            }
                            if (hub != null && hub.IsConnectionDisposing)
                            {
                                if (settingChange.ContainsKey(hub.Id))
                                {
                                    settingChange.Remove(hub.Id);
                                    return;
                                }

                                hub.HubUpdate -= hub_HubUpdate;
                                hubs.Remove(onlineStatus.HubId);
                                // TODO : We should realy realy 
                                if (tab != null)
                                    tab.MessagePanel.ActionUpdate -= MessagePanel_ActionUpdate;
                            }
                        }
                    }
                    break;
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            //base.OnClosing(e);
            e.Cancel = !Close;
            if (!Close)
                this.Hide();
        }

        private void MessageWindow_Load(object sender, EventArgs e)
        {
            statusImageList.Images.Add(Program.Images.GetBitmap("connecting.gif"));
            statusImageList.Images.Add(Program.Images.GetBitmap("online.gif"));
            statusImageList.Images.Add(Program.Images.GetBitmap("offline.gif"));
        }
    }
}
